package com.ltmall.api.redis;

import com.alibaba.fastjson.JSONObject;
import com.ltmall.api.util.HttpRequestUtil;
import com.ltmall.api.weixin.pay.Constants;
import com.ltmall.api.weixin.util.Constant;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import redis.clients.jedis.Jedis;

public class RedisUtil {

    /**
     * Redis服务器IP
     */
    private static final String ATTR = Constant.getAttr();

    /**
     * Redis的端口号
     */
    private static final int PORT = Constant.getPort();

    /**
     * 访问密码
     */
    private static final String AUTH = Constant.getAuth();

    private static final String ACCESS_TOKEN_KEY = Constant.getAccessTokenKey();

    private static final String TEST_ACCESS_TOKEN_KEY = Constant.getAccessTestTokenKey();

    private static Logger log = LogManager.getLogger(RedisUtil.class);

    public static Jedis getInstance() {
        Jedis jedis = new Jedis(ATTR, PORT);
        try {
            jedis.auth(AUTH);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jedis;
    }

    public static String getAccessToken() {
        Jedis jedis = getInstance();

        String cacheWechatAccessToken = ACCESS_TOKEN_KEY;

        String accessToken = jedis.get(cacheWechatAccessToken);
        log.info("尝试获取当前redis中保存的accessToken");
        if (accessToken == null || accessToken.toString().equals("nil")) {
            int expireSeconds = 1800;
            JSONObject accessTokenJson = HttpRequestUtil.sendGet(
                    "https://api.weixin.qq.com/cgi-bin/token", "grant_type=client_credential&appid="
                            + Constants.OA_APP_ID + "&secret="
                            + Constants.OA_APP_SECRET);
            accessToken = accessTokenJson.get("access_token").toString();
            jedis.set(cacheWechatAccessToken, accessToken);
            jedis.expire(cacheWechatAccessToken, expireSeconds);
            log.info("redis中保存的accessToken已经过期，重新接口获取:" + accessToken);
            return accessToken;
        } else {
            log.info("redis中保存的accessToken是有效的:" + accessToken);
            return accessToken;
        }
    }

    /*public static boolean isSetGoodDetail(String goodsId) {
        Jedis jedis = getInstance();
        String detailId = jedis.get("GOOD_DETAIL_ID_" + goodsId);
        if (StringUtils.isNotNull(detailId)) {
            return true;
        } else {
            return false;
        }
    }

    public static void setGoodDetail(String goodsId, JsonGoodsDetail detali) {
        Jedis jedis = getInstance();

        jedis.set("GOOD_DETAIL_ID_" + goodsId, detali.getActivityName());

    }

    public static String getGoodDetail(String goodsId, JsonGoodsDetail detali) {

        log.info("尝试获取当前redis中保存的accessToken");
        Jedis jedis = getInstance();

        //【1】获取商品信息1
        String accessToken = jedis.get(goodsId + "_1");
        detali.setActivityGoods(activityGoods);

        //【2】获取商品信息1
        String accessToken = jedis.get(goodsId + "_1");
        detali.setActivityGoods(activityGoods);

        log.info("redis中保存的accessToken是有效的:" + accessToken);
        return accessToken;
    }*/

    public static String getTestAccessToken() {
        Jedis jedis = getInstance();

        String cacheWechatAccessToken = TEST_ACCESS_TOKEN_KEY;

        String accessToken = jedis.get(cacheWechatAccessToken);
        log.info("尝试获取当前redis中保存的accessToken");
        if (accessToken == null || accessToken.toString().equals("nil")) {
            int expireSeconds = 1800;
            JSONObject accessTokenJson = HttpRequestUtil.sendGet(
                    "https://api.weixin.qq.com/cgi-bin/token", "grant_type=client_credential&appid="
                            + Constants.DEBUG_OA_APP_ID + "&secret="
                            + Constants.DEBUG_OA_APP_SECRET);
            accessToken = accessTokenJson.get("access_token").toString();
            jedis.set(cacheWechatAccessToken, accessToken);
            jedis.expire(cacheWechatAccessToken, expireSeconds);
            log.info("redis中保存的accessToken已经过期，重新接口获取:" + accessToken);
            return accessToken;
        } else {
            log.info("redis中保存的accessToken是有效的:" + accessToken);
            return accessToken;
        }
    }

    public static String refreshAccessToken() {
        Jedis jedis = getInstance();
        String cacheWechatAccessToken = ACCESS_TOKEN_KEY;
        String accessToken = jedis.get(cacheWechatAccessToken);
        log.info("尝试强制刷新缓存的accesstoken！过期时间1800秒");
        int expireSeconds = 1800;
        JSONObject accessTokenJson = HttpRequestUtil.sendGet(
                "https://api.weixin.qq.com/cgi-bin/token", "grant_type=client_credential&appid="
                        + Constants.OA_APP_ID + "&secret="
                        + Constants.OA_APP_SECRET);
        accessToken = accessTokenJson.get("access_token").toString();
        jedis.set(cacheWechatAccessToken, accessToken);
        jedis.expire(cacheWechatAccessToken, expireSeconds);
        log.info("redis中保存的accessToken刷新成功，新token:" + accessToken);
        return accessToken;
    }

    public static void oAuthAccessTokenSet(String openid, String accessToken, int expireTime) {
        Jedis jedis = getInstance();
        jedis.set(openid, accessToken);
        jedis.expire(openid, expireTime);
    }

    /**
     * 无过期时间的小程序授权缓存写入
     *
     * @param openid
     * @param accessToken
     */
    public static void oAuthAccessTokenSetForever(String openid, String accessToken) {
        Jedis jedis = getInstance();
        jedis.set(openid, accessToken);
    }

    public static String oAuthAccessTokenGet(String openid) {
        String accessToken = jedisGet(openid);
        if (accessToken == null) {
            accessToken = oAuthAccessTokenByRefreshToken(openid);
            if (accessToken.equals("error")) {
                return "error";
            } else {
                return accessToken;
            }
        } else {
            return accessToken;
        }
    }

    public static void jedisSet(String key, String value) {
        Jedis jedis = getInstance();
        jedis.set(key, value);
    }

    public static String jedisGet(String key) {
        Jedis jedis = getInstance();
        return jedis.get(key);
    }

    public static String oAuthAccessTokenByRefreshToken(String openid) {
        String refreshToken = jedisGet(openid + "refresh_token");
        JSONObject accessToken = HttpRequestUtil.sendGet(
                "https://api.weixin.qq.com/sns/oauth2/refresh_token",
                "appid=" + Constants.appIDGet() + "&grant_type=refresh_token&refresh_token="
                        + refreshToken);
        try {
            accessToken.getString("errcode");
            return "error";
        } catch (Exception e) {
        }
        return accessToken.getString("access_token");
    }
}
